﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using Meqs.Entity;
using Meqs.Logic;
using Meqs.Logic.Interface;
using Meqs.Utilities;
using Meqs.Entity.Views;

public partial class Credit_Teacher_Reprots_ScoreInMonth : ContainerBasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindSchoolYear();

            selYear_TextChanged(selYear, new EventArgs());

            //BindClass(SchoolCommon.Sch_SchoolInfo.SchoolYear, SchoolCommon.Sch_SchoolInfo.SchoolTerm);
            //BindMonth(SchoolCommon.Sch_SchoolInfo.SchoolYear, SchoolCommon.Sch_SchoolInfo.SchoolTerm);

            btnQuery_Click(btnQuery, new EventArgs());
        }
 
    }

    protected void selYear_TextChanged(object sender, EventArgs e)
    {
        int nYear;
        int nTerm;

        string[] outString = selYear.SelectedValue.Split(new char[] { ',' });
        if (outString.Length != 2)
            //throw new Exception("orz The param is worng");
            return;

        if (!Int32.TryParse(outString[0], out nYear))
            //throw new Exception("orz The param is worng");
            return;

        if (!Int32.TryParse(outString[1], out nTerm))
            //throw new Exception("orz The param is worng");
            return;

        BindClass(nYear, nTerm);
        BindMonth(nYear, nTerm);
        
    }

    /// <summary>
    /// 绑定学期下拉框
    /// </summary>
    protected void BindSchoolYear()
    {
        //Hashtable ht = new Hashtable();
        //ht.Add("SchoolMark", SchoolMark);
        //IList<StuCauseEvalHistory> historyList = Container<IStuCauseEvalHistoryLogic>.Instance.FindAll(ht);
        //if (historyList == null || historyList.Count < 1)
        //{
        //    selYear.Items.Add(new ListItem("没有历史数据", "-1"));
        //}
        //IList<String> strList = new List<String>();
        //if (historyList != null)
        //    foreach (StuCauseEvalHistory history in historyList)
        //    {
        //        String value = String.Format("{0},{1}", history.SchoolYear, history.Term);
        //        if (strList.Contains(value)) continue;
        //        int year;
        //        int term;
        //        if (!Int32.TryParse(history.SchoolYear.ToString(), out year))
        //            return;
        //        if (!Int32.TryParse(history.Term.ToString(), out term))
        //            return;
        //        String str = Common.ConvertYearAndTerm(year, term);
        //        selYear.Items.Add(new ListItem(str, value));
        //        strList.Add(value);
        //    }
        SchoolInfo si = SchoolCommon.Sch_SchoolInfo;
        Hashtable ht = new Hashtable();
        ht.Add("SchoolMark", si.SchoolMark);
        IList<TermInfo> terms = Container<ITermInfoLogic>.Instance.FindAll(ht);
        foreach (TermInfo term in terms)
        {
            String str = Common.ConvertYearAndTerm(term.SchoolYear, term.Term);
            String value = String.Format("{0},{1}", term.SchoolYear, term.Term);
            selYear.Items.Add(new ListItem(str, value));
        }
    }

    /// <summary>
    /// 绑定班级下拉框
    /// </summary>
    protected void BindClass(int schoolYear, int term)
    {
        selClass.Items.Clear();
        IList<ClsInfo> schoolList = Container<IClassHistoryLogic>.Instance.FindClassesInSchoolYear(schoolYear, SchoolMark, null);
        ListSort<ClsInfo> sortList = new ListSort<ClsInfo>(schoolList, "Grade");
        schoolList = sortList.Sort();
        if (schoolList == null || schoolList.Count < 1)
            return;


        foreach (ClsInfo info in schoolList)
        {
            String str = "";
            switch (info.Grade)
            {
                case 1:
                    str = "一年级";
                    break;
                case 2:
                    str = "二年级";
                    break;
                case 3:
                    str = "三年级";
                    break;
                case 4:
                    str = "四年级";
                    break;
                case 5:
                    str = "五年级";
                    break;
                case 6:
                    str = "六年级";
                    break;
                case 7:
                    str = "初一";
                    break;
                case 8:
                    str = "初二";
                    break;
                case 9:
                    str = "初三";
                    break;
                case 10:
                    str = "高一";
                    break;
                case 11:
                    str = "高二";
                    break;
                case 12:
                    str = "高三";
                    break;
            }
            if (Common.GetUserInfo().UserType != 5)
            {
                #region 班级过滤
                List<int> enableClassList = SchoolCommon.CanViewClasses((int)SecurityTable.Security.Credit_CanView, SchoolCommon.Sch_SchoolInfo.SchoolYear, SchoolCommon.Sch_SchoolInfo.SchoolTerm);
                bool enableClass = false;
                if (!(enableClassList == null))
                {
                    foreach (int i in enableClassList)
                    {
                        if (info.RID == i)
                        {
                            enableClass = true;
                            break;
                        }
                    }
                    if (!enableClass)
                        continue;
                }
                #endregion
            }
            selClass.Items.Add(new ListItem(String.Format("{0}({1})班", str, info.ClsNo), info.RID.ToString()));
        }
    }

    /// <summary>
    /// 绑定月份下拉框
    /// </summary>
    protected void BindMonth(int schoolYear, int term)
    {
        selSubject.Items.Clear();

        Hashtable ht = new Hashtable();
        ht.Add("SchoolMark", SchoolMark);
        ht.Add("SchoolYear", schoolYear);
        ht.Add("Term", term);
        IList<TermInfo> list = Container<ITermInfoLogic>.Instance.FindAll(ht);
        if (list == null || list.Count < 1)
        {
            selSubject.Items.Add(new ListItem("-----", "-1"));
            return;
        }
        DateTime? dts = list[0].StartDate;

        if (term == 2)
        {
            schoolYear++;
            term = 1;
        }
        else
        {
            term = 2;
        }

        DateTime? dte = null;
        ht = new Hashtable();
        ht.Add("SchoolMark", SchoolMark);
        ht.Add("SchoolYear", schoolYear);
        ht.Add("Term", term);
        list = Container<ITermInfoLogic>.Instance.FindAll(ht);
        if (list == null || list.Count < 1)
            dte = DateTime.Now;
        else
            dte = list[0].StartDate;

        for (int i = 0; ; i++)
        {
            if (dts > dte && (dts.Value.Month > dte.Value.Month || dts.Value.Year > dte.Value.Year))
                break;
            selSubject.Items.Add(new ListItem(dts.Value.ToString("yyyy-MM"), dts.Value.Month.ToString()));
            dts = dts.Value.AddMonths(1);
        }
    }

    /// <summary>
    /// 查询按钮事件
    /// </summary>
    protected void btnQuery_Click(object sender, EventArgs e)
    {
        int nYear = 0;
        int nTerm = 0;
        int nClassID = 0;
        String date;
        //CauseFormula cf = new CauseFormula(SchoolMark);

        string[] outString = selYear.SelectedValue.Split(new char[] { ',' });
        if (outString.Length != 2)
            return;

        if (!Int32.TryParse(outString[0], out nYear))
            return;

        if (!Int32.TryParse(outString[1], out nTerm))
            return;

        if (!Int32.TryParse(selClass.SelectedValue, out nClassID))
            return;

        date = selSubject.SelectedItem.Text;

        // 查询数据
        // 科目数据
        List<GlobalCauseInfo> allCauseList = new List<GlobalCauseInfo>();
        IGlobalCauseInfoLogic causeLogic = Container<IGlobalCauseInfoLogic>.Instance;
        allCauseList = (List<GlobalCauseInfo>)causeLogic.SelectSchoolCause(SchoolMark);
        Hashtable ht = new Hashtable();
        ht.Add("RID", nClassID);
        ht.Add("SchoolMark", SchoolMark);
        IList<ClsInfo> cilist = Container<IClsInfoLogic>.Instance.FindAll(ht);
        

        ht = new Hashtable();
        ht.Add("Grade", cilist[0].Grade);
        ht.Add("SchoolMark", SchoolMark);
        IList<CouseGradeInfo> cgList = Container<ICouseGradeInfoLogic>.Instance.FindAll(ht);

        IList<GlobalCauseInfo> sl = new List<GlobalCauseInfo>();
        foreach (GlobalCauseInfo info in allCauseList)
        {
            foreach (CouseGradeInfo gradeInfo in cgList)
            {
                if (gradeInfo.CourseID == info.RID)
                {
                    sl.Add(info);
                    break;
                }
            }
        }


        //获取学分查询结果
        int nDateYear = 0;
        int nDataMonth = 0;
        outString = date.Split(new char[] { '-' });

        
        if (!Int32.TryParse(outString[0], out nDateYear))
            return;

        if (!Int32.TryParse(outString[1], out nDataMonth))
            return;

        DateTime dt = new DateTime(nDateYear, nDataMonth, 1);

        IStuCausePersonCatchLogic logic = Container<IStuCausePersonCatchLogic>.Instance;
        List<CreditReport> reportList = (List<CreditReport>)logic.GetCreditByMonth(SchoolMark, nClassID, nYear, nTerm, dt, dt.AddMonths(1));
        IList<MoralityScoreInTermView> msv = Container<IMoralityPersonCatchLogic>.Instance.FindMoralityScoreInTerm(SchoolMark, nYear, nTerm, null, nClassID);
        Dictionary<int, String> subjectPair = new Dictionary<int, String>();
        // TODO : 构造表格
        tbResult.Rows.Clear();
        int width = 0;
        #region 构造表头
        TableHeaderRow h1row = new TableHeaderRow();
        TableHeaderCell h1cell = new TableHeaderCell();
        h1cell.Text = Common.ConvertYearAndTerm(nYear, nTerm) + "&nbsp;&nbsp;"
                        + cilist[0].ClsName + "&nbsp;&nbsp;"
                        + nDateYear + "年" + nDataMonth+"月";
        h1cell.ColumnSpan = sl.Count + 3;
        h1cell.CssClass = "FixedRowCol";
        h1row.Cells.Add(h1cell);
        tbResult.Rows.Add(h1row);


        TableHeaderRow hrow = new TableHeaderRow();
        TableHeaderCell hcell = new TableHeaderCell();
        hcell.Text = "学号";
        hcell.Style[HtmlTextWriterStyle.Width] = "80px";
        hcell.CssClass = "FixedRowCol";
        width += 80;
        hrow.Cells.Add(hcell);

        hcell = new TableHeaderCell();
        hcell.Text = "姓名";
        hcell.Style[HtmlTextWriterStyle.Width] = "80px";
        hcell.CssClass = "FixedRowCol";
        width += 80;
        hrow.Cells.Add(hcell);

        foreach (GlobalCauseInfo info in sl)
        {
            hcell = new TableHeaderCell();
            hcell.Text = info.CauseName;
            hcell.Style[HtmlTextWriterStyle.Width] = "50px";
            width += 50;
            hcell.CssClass = "FixedRow";
            hrow.Cells.Add(hcell);
            subjectPair.Add(info.RID, info.CauseName);
        }
        hcell = new TableHeaderCell();
        hcell.Text = "学生德育";
        hcell.Style[HtmlTextWriterStyle.Width] = "60px";
        width += 60;
        hcell.CssClass = "FixedRow";
        hrow.Cells.Add(hcell);
        tbResult.Rows.Add(hrow);
        tbResult.Style[HtmlTextWriterStyle.Width] = String.Format("{0}px", width);
        if (reportList.Count < 1)
            return;
        #endregion

        #region 填充内容
        TableRow row = new TableRow();
        TableCell cell;
        int oldid = -1;
        Dictionary<int, double> scoreList = new Dictionary<int, double>();
        foreach (CreditReport view in reportList)
        {
            if (view.StuID != oldid)
            { // 新行
                if (oldid != -1)
                { // 非第一行
                    foreach (GlobalCauseInfo info in sl)
                    {
                        cell = new TableCell();

                        if(scoreList.ContainsKey(info.RID))
                            cell.Text = scoreList[info.RID] > 100? "100":scoreList[info.RID].ToString();

                        row.Cells.Add(cell);
                    }
                    cell = new TableCell();
                    double md = getm(msv, oldid, dt);
                    md = md > 100 ? 100 : md;
                    cell.Text =( md == 0?"":md.ToString());

                    row.Cells.Add(cell);
                    tbResult.Rows.Add(row);
                }
                row = new TableRow();
                cell = new TableCell();
                cell.Text = view.StuCode;
                cell.CssClass = "FixedCol";
                row.Cells.Add(cell);

                cell = new TableCell();
                cell.Text = view.StuName;
                cell.CssClass = "FixedCol";
                row.Cells.Add(cell);

                scoreList = new Dictionary<int, double>();

            }
            if (!scoreList.ContainsKey(view.CauseID))
                scoreList.Add(view.CauseID, view.Score);
                //scoreList.Add(view.CauseID, cf.GetExpressScore(view.Score));
                //scoreList.Add(view.CauseID, Math.Round(cf.GetExpressScore(view.Score) / (cf.ExpressWeight / 100), 2));
            
            oldid = view.StuID;
        }
        // 计算最后一行
        foreach (GlobalCauseInfo info in sl)
        {
            cell = new TableCell();
            if (scoreList.ContainsKey(info.RID))
                cell.Text = scoreList[info.RID].ToString();

            row.Cells.Add(cell);
        }
        cell = new TableCell();
        double mdd = getm(msv, oldid, dt);
        cell.Text = (mdd == 0 ? "" : mdd.ToString());

        row.Cells.Add(cell);
        tbResult.Rows.Add(row);


        #endregion
    }
    private double getm(IList<MoralityScoreInTermView> msv,int stuid,DateTime dt)
    {
        foreach (MoralityScoreInTermView m in msv)
        {
            if (stuid == m.StuID && m.StartTime.Year == dt.Year && dt.Month == m.StartTime.Month)
            {
                return m.Score;
            }
        }
        return 0;
    }
    [WebMethod]
    public static string GetExcel(ExcelTableCell[][] cells)
    {
        string temp_path = HttpContext.Current.Server.MapPath("../../../");
        string save_path = temp_path + "download\\" + DateTime.Now.Ticks.ToString() + "_scoreInMonth.xls";
        HttpContext.Current.Session["filepath"] = save_path;
        ExcelUtil.ExcelExport(save_path, DateTime.Now.Ticks.ToString() + "学生每月学分公示", 2, 0, cells);
        return "";
    }
}
